<template>
	<view class="content">
		<hs-status-bar></hs-status-bar>
		<top-bar :title="'caseform'" :haveBack="false" @dbClick="dbClick"></top-bar>
		<view class="list">
			<hs-phoneModel material-type="product" :showRight="true" :materialList="materialList" ref="phoneModel"
				@handleSelectModel="selectModel" @handleSelectTransparent="selectTransparent"
				@handleSelectMaterial="selectMaterial"></hs-phoneModel>

			<scroll-view scroll-anchoring refresher-default-style="black" refresher-background="#F6F6F6"
				:refresher-triggered="triggered" :refresher-threshold="100" @refresherrefresh="onRefresh"
				@refresherrestore="onRestore" refresher-enabled scroll-y scroll-with-animation
				@scrolltolower="scrolltolower" class="scroll" :scroll-top="scrollTop">
				<!-- <view class="select">
					<input type="text" />
					<view class="btn-edit">
						<navigator url="/pages/diy/diyPhoneCase">
							图案
							<br />
							定制
						</navigator>

					</view>
				</view> -->
				<view class="list-box">

					<view class="product-item" v-for="item of templateList" :key="item.id">
						<navigator :url="`/pages/product/productDetail?id=${item.id}`">
							<view class="item">
								<image :src="item.imageUrl" lazy-load mode="aspectFit" style="background-color: #eee;"
									class="picture" :class="{ loading: !item.isLoaded }" @load="handleImageLoad(item)"
									:style="{ background: item.isLoaded ? 'transparent' : '#eee' }"></image>
								<!-- <view class="title">
									{{item.name}}
								</view> -->
								<view class="price">
									￥{{ item.price }}
								</view>
							</view>
						</navigator>
					</view>
				</view>
				<view class="hs-p-b-20" v-if="!isEmpty">
					<u-loadmore :status="status" />
				</view>
				<u-empty v-if="isEmpty" mode="car" text="暂无数据" icon="/static/images/icon/product.jpg">
					<view style="margin-top: 40rpx;text-decoration-line: underline;" @click="toEdit">
						没有满意的？试试自己定制
					</view>
				</u-empty>
			</scroll-view>
			<!-- <trolley ref="trolley" @tolleyHide="tolleyHide" :scollUnder="93"></trolley>
			<view class="shopping-trolley" :class="{tShow,hide:trolleySum.allCount == 0&&!tShow}">
				<view>
					<hs-badge :count="trolleySum.allCount" v-show="trolleySum.allCount"></hs-badge>
					<image src="@/static/images/icon/trolley.png" mode="" @click="showTrolley" class="car"></image>
				</view>
				<button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" class="get-phone"
					v-if="!phoneNumber">授权并获取手机号</button>
				<text class="price">￥{{trolleySum.productAmount}}</text>
				<view class="to-order" @click="$u.debounce(toOrder)"
					:style="{color:trolleySum.productCount?'#3D3D3D':'#999'}">
					{{trolleySum.productCount == 0 ?'不可结算':'去结算'}}

				</view>

			</view> -->
		</view>
	</view>
</template>

<script>
import {
	getTemplateList
} from '@/api/product.js';
import eventTracking from "@/utils/eventTracking.js"; //埋点

import {
	getStyleList,
	getSkuList
} from '@/api/custom.js';
import {
	decryptPhoneNumber
} from '@/api/user.js';
import {
	mapGetters,
	mapActions,
	mapMutations
} from 'vuex'
export default {
	data() {
		return {
			scrollTop: 0,
			triggered: false,
			templateList: [],
			styleList: [],
			materialList: [],
			activeStyleList: [],
			activeMaterial: '',
			activeMaterialIndex: 0,
			activeMaterialName: '材质',
			pageSize: 10,
			isEmpty: false,
			tShow: false,
			status: "loading",
			templateListCache: new Set(), // 用于跟踪已加载过的图片
			lastProductMaterialMap: {}, // 增加最后一次记录的机型和材质，用于优化切换
			_isManualSelect: false, // 是否允许调用接口
			_selectTransparent: null,
		}
	},
	computed: {
		...mapGetters(['phoneNumber', 'phoneModelId', 'getProductMaterial'])
	},
	methods: {
		...mapMutations(['setProductMaterial']),
		// 下拉刷新
		// onRefresh() {
		// 	if (this.triggered) return
		// 	this.triggered = true;
		// 	// 重置所有项目的加载状态
		// 	this.templateList.forEach(item => {
		// 		this.$set(item, 'isLoaded', false)
		// 	})
		// 	setTimeout(() => {
		// 		this.getTemplateList();
		// 	}, 500)
		// },
		onRefresh() {
			if (this.triggered) return
			this.triggered = true;

			// 仅重置旧数据的加载状态（如果保留缓存数据）
			this.templateList.forEach(item => {
				if (item.isLoaded) this.$set(item, 'isLoaded', false)
			});

			setTimeout(() => {
				this.getTemplateList();
			}, 500)
		},
		// 复位
		onRestore() {
			this.triggered = false;
		},
		// 滑动到底部
		scrolltolower() {
			console.log('scrolltolower', this.templateList);
			if (this.templateList.length < this.pageSize) return
			this.getTemplateList(this.templateList[this.templateList.length - 1].id)
		},
		// 选择手机型号
		selectModel(data) {
			if (this.phoneModelId === data) { // 增加机型比对
				console.log('机型未变化')
				return
			}
			console.log(data);
			// this._isManualSelect = true; // 手动切换机型，防止连续触发多次接口
			this.getSkuListFun(data).finally(() => {
				// this._isManualSelect = false
			});
			uni.$u.debounce(() => {
				this.onRefresh()
			})
		},
		selectTransparent(data) {
			if (this._selectTransparent != data.transparent) {
				this._selectTransparent = data.transparent
				this.onRefresh()
			}
		},

		async getSkuListFun(phoneModelId) {
			const { data } = await getSkuList({
				materialMap: { 11: phoneModelId || this.phoneModelId },
				pageSize: 50
			})

			this.materialList = data
			const storedMaterial = this.getProductMaterial

			// 智能匹配策略
			// const idx = data.findIndex(item => 
			// 	storedMaterial?.materialMap[10] === item.materialMap[10]
			// )

			// const finalIndex = idx !== -1 ? 
			// 	idx : 
			// 	data.findIndex(item => item.defaulted)

			let finalIndex = 0
			if (data.length > 0) {

				// 使用可选链和空值合并操作符
				const historyMaterialId = storedMaterial?.materialMap?.[10] ?? null // 先查找历史记录
				// 分步查找策略
				finalIndex = data.findIndex(i =>
					i.materialMap?.[10] === historyMaterialId
				)

				// 未找到历史材质时查找默认项
				if (finalIndex === -1) {
					finalIndex = data.findIndex(item => item.defaulted)
				}

				// 双重保险：当默认项也不存在时取首项
				finalIndex = finalIndex >= 0 ? finalIndex : 0


				finalIndex = Math.max(finalIndex, 0) // 确保下标不小于0
			}

			// this.selectMaterial(data[finalIndex], finalIndex)
			console.log('finalIndex1', finalIndex);
			console.log('finalIndex2', data[finalIndex]);
			console.log('finalIndex3', data[finalIndex].id);
			this.selectMaterial(data[finalIndex], data[finalIndex].id)
		},
		// 选择材质
		selectMaterial(data, index) {
			// uni.setStorageSync('defaultMaterial', {
			// 	data,
			// 	index
			// })
			console.log('000', data);
			console.log('000id', data.id);
			this.setProductMaterial(data)

			// 需要新增的setCurrentMaterial用途
			this.$store.commit('setCurrentMaterial', { // 存储标准化材质参数（用于跨页面传递）
				materialMap: {
					10: data.materialMap[10], // 材质ID
					11: this.phoneModelId    // 机型ID
				}
			})
			this.activeMaterial = data?.materialMap[10]
			// this.$refs.phoneModel.activeMaterialIndex = index
			this.$refs.phoneModel.activeMaterialIndex = data.id
			console.log('000list', this.materialList);
			// console.log('0001',this.materialList[data.id]);
			if (this.materialList.length > 0) {
				// this.activeMaterialName = this.materialList[index]?.name
				let [{ ...item }] = this.materialList.filter((d) => d.name == data.name)
				console.log('item', item);
				this.activeMaterialName = item.name
				console.log('filter', this.activeMaterialName);
				this.$refs.phoneModel.name = item.name
				this.$refs.phoneModel.baseImageUrl = item.baseImageUrl
				this.$refs.phoneModel.frameImageUrl = item.frameImageUrl
				let extraData = item.materialMap
				eventTracking.event('SWITCH_MATERIAL', 'pages/product', extraData)
			}
			this.$refs.phoneModel.materialListShow = false
			uni.$u.debounce(() => {
				this.onRefresh()
			})
		},
		onTabItemTap(e) {
			console.log(e, '监听点击的tab')
			eventTracking.event('CASEFORM_LIST', e.pagePath,);
		},
		// 获取模板列表
		getTemplateList(lastId) {
			// 新增参数校验
			if (!this.activeMaterial || !this.phoneModelId) {
				this.isEmpty = true
				return this.$u.toast('请先选择机型和材质')
			}
			this.status = "loading";
			getTemplateList({
				pageSize: this.pageSize,
				materialMap: {
					10: this.activeMaterial,
					11: this.phoneModelId || uni.getStorageSync('userInfo').phoneModelId
				},
				type: 1,
				lastId,
				transparent: this._selectTransparent
			}).then(res => {
				this.templateList = !lastId ? res.data : this.templateList.concat(res.data)


				// const newData = res.data.map(v => ({...v, isLoaded: false}))
				// this.templateList = !lastId ? newData : this.templateList.concat(newData)

				// const newData = res.data.map(v => ({
				// 	...v,
				// 	isLoaded: this.templateListCache?.has(v.id) // 检查缓存
				// }));
				// // 更新缓存
				// this.templateListCache = new Set(newData.map(v => v.id));
				// this.templateList = !lastId ? newData : [...this.templateList, ...newData];

				// 生成带时间戳的新URL强制重新加载
				// const timestamp = Date.now();
				// const newData = res.data.map(v => ({
				// 	...v,
				// 	imageUrl: `${v.imageUrl}?t=${timestamp}`, // 强制刷新图片
				// 	isLoaded: !lastId ? false : this.templateListCache.has(v.id)
				// }));

				// // 下拉刷新时清空缓存
				// if (!lastId) this.templateListCache = new Set();

				// newData.forEach(v => this.templateListCache.add(v.id));
				// // 使用vue.set确保响应式更新
				// if (!lastId) {
				// 	this.templateList = newData;
				// } else {
				// 	const newIds = new Set(newData.map(v => v.id));
				// 	const filteredList = this.templateList.filter(v => !newIds.has(v.id));
				// 	this.templateList = [...filteredList, ...newData];
				// }

				if (this.templateList.length == 0) {
					this.isEmpty = true
					this.status = "nomore";
				} else if (res.data.length < 10) {
					this.status = "nomore";
					this.isEmpty = false
				} else {
					this.status = "loadmore";
					this.isEmpty = false
				}
				this.triggered = false

			}).catch(err => {
				this.status = "nomore";
				this.onRestore()
			})
		},
		handleImageLoad(item) {
			this.$set(item, 'isLoaded', true)
		},
		// 双击回到顶部
		dbClick() {
			this.scrollTop = this.scrollTop == -1 ? 0 : -1
		},
		toEdit() {
			uni.navigateTo({
				url: '/pages/diy/diyPhoneCase'
			})
		},
		getRefreshes() {
			// 获取存储数据
			const storedMaterial = this.getProductMaterial
			this.$nextTick(async () => {
				await this.getSkuListFun() // 等待材质列表加载

				if (storedMaterial && this.materialList.length > 0) {
					console.log('currentMaterial22', this.materialList);
					const validIndex = this.materialList.findIndex(item =>
						item.materialMap?.[10] === storedMaterial.materialMap?.[10]
					)
					if (validIndex > -1) {
						this.selectMaterial(this.materialList[validIndex], validIndex)
					}
				}
			})
		},
	},
	onLoad() {
		// 初始记录当前机型和材质
		this.lastProductMaterialMap = this.getProductMaterial?.materialMap ?? {};
		// uni.$u.debounce(() => {
		// 	this.getMaterialListFun()
		// })


	},
	onShow() {

		const currentMaterialMap = this.getProductMaterial?.materialMap ?? {}; // 当前机型和材质
		const lastMap = this.lastProductMaterialMap || {}; // 增加空对象保护
		// 安全读取键值（使用空值合并运算符）
		const current10 = currentMaterialMap[10] ?? null;
		const last10 = lastMap[10] ?? null;
		// 精确比较关键字段（材质ID 10和机型ID 11）

		if (current10 !== last10) {
			console.log('关键材质变化，自动刷新');
			this.getRefreshes();
		}
		// this.$nextTick(() => {
		// 	this.getSkuListFun()
		// });

		// // 机型变化检测
		// if(Object.keys(this.lastProductMaterialMap).length !== 0 && (this.lastProductMaterialMap[10] !== currentMaterialMap[10] || this.lastProductMaterialMap[11] !== currentMaterialMap[11] ) ) {
		// 	console.log('检测到机型变化，自动刷新');
		// 	this.getRefreshes(); // 触发下拉刷新
		// }else{
		// 	console.log('机型未变化，无需刷新');
		// }

		// 记录当前机型
		this.lastProductMaterialMap = { ...currentMaterialMap }; // 深度克隆避免引用关联


	},
	mounted() {
		this.$nextTick(() => {
			this.getSkuListFun()
		});
	},

	onHide() {
		this.lastProductMaterialMap = this.getProductMaterial?.materialMap ?? {};//切换底部tab栏时，保存上一次的材质
	},
	// 在页面卸载时清理缓存
	onUnload() {
		// imageCache.clear();
		this.templateList.forEach(item => {
			item.imageUrl = null;
		});
	},
	onShareAppMessage() {
		return {
			title: '我发现了一款可以DIY定制手机壳的小程序，快来看看吧',
			path: `/pages/index/index?page=product`,
		}
	},
	watch: {
		phoneModelId(newVal, oldVal) {
			// if (this._isManualSelect || newVal === oldVal) return;// 防止重复触发
			if (newVal === oldVal) return;// 防止重复触发
			this.getSkuListFun(newVal).then(() => {
				const hasPrevious = this.materialList.some(item =>
					item.materialMap[10] === this.getProductMaterial?.materialMap[10]
				)

				if (!hasPrevious) {
					this.setProductMaterial(
						this.materialList.find(item => item.defaulted)
					)
				}
			})
		}
	},
	// watch: {
	// 	phoneModelId(newVal) {
	// 		this.getMaterialList(newVal)
	// 	},
	// 	getCurrentMaterial(newVal) {
	// 		const idx = this.materialList.findIndex(item => 
	// 		item.materialMap[10] === newVal?.materialMap[10]
	// 		)
	// 		this.selectMaterial(newVal, Math.max(idx, 0))
	// 	}
	// }

	// onShareTimeline() {
	// 	return {
	// 		title: '我发现了一款可以DIY定制手机壳的小程序，快来看看吧',
	// 		path: `/pages/index/index?page=product`,
	// 	}
	// }
}
</script>

<style lang="scss">
.content {
	height: 100%;
	width: 100%;
	display: flex;
	flex-direction: column;

	.menu {
		width: 100%;
		background: #fff;
		/* height: 60px; */
	}
}

.list {
	width: 100%;
	flex-grow: 1;
	overflow: hidden;
	display: flex;
	flex-direction: column;

	.scroll {
		height: 100%;
		overflow: hidden;
		flex-grow: 1;
	}

	.select {
		height: 73.5rpx;
		width: 100%;
		display: flex;
		margin-top: 17rpx;

		input {
			height: 100%;
			flex-grow: 1;
			background-color: #fff;
			border-radius: 17rpx;
			margin-left: 17rpx;
			border: 1px solid #EBEBEB;
			background-image: url(@/static/images/icon/sousuo.png);
			background-size: 42rpx;
			background-repeat: no-repeat;
			background-position: calc(100% - 21rpx);
			padding: 17rpx 79rpx 17rpx 42rpx;
			box-sizing: border-box;
		}

		.btn-edit {
			height: 73.5rpx;
			width: 73.5rpx;
			margin: 0 17rpx;
			border-radius: 17rpx;
			background-color: #fff;
			text-align: center;
			font-size: 22rpx;
			color: #8a8a8a;
			padding-top: 7rpx;
			border: 1px solid #EBEBEB;
		}
	}

	// .material-content {
	// 	display: flex;
	// 	padding: 10rpx;
	// 	background-color: #fff;
	// 	position: relative;

	// 	.phone-model {
	// 		height: 50rpx;
	// 		line-height: 50rpx;
	// 		font-size: 28rpx;
	// 		margin: 26rpx 35rpx 0;
	// 		position: relative;
	// 		color: #979797;
	// 		flex-shrink: 0;

	// 		.phone-select {
	// 			display: inline-block;
	// 			border-radius: 50rpx;
	// 			border: 2rpx solid #333;
	// 			padding: 0 17rpx;
	// 			font-size: 26rpx;
	// 			height: 50rpx;

	// 			text {
	// 				font-weight: bold;
	// 				color: #333;
	// 			}

	// 			.text1 {
	// 				margin-left: 17rpx;
	// 				font-size: 20rpx;
	// 			}
	// 		}
	// 	}

	// 	.material-name {
	// 		height: 100rpx;
	// 		display: flex;
	// 		flex-grow: 1;

	// 		image {
	// 			height: 100%;
	// 			width: 100rpx;
	// 			position: absolute;
	// 		}

	// 		text {
	// 			font-size: 28rpx;
	// 			margin: auto;
	// 			margin-left: 100rpx;
	// 		}

	// 		.text1 {
	// 			margin-left: 17rpx;
	// 			font-size: 20rpx;
	// 		}
	// 	}

	// 	.material-list {
	// 		height: 300rpx;
	// 		width: 100%;
	// 		background-color: #fff;
	// 		position: absolute;
	// 		bottom: -300rpx;
	// 		left: 0;
	// 		z-index: 999;
	// 		box-shadow: -1rpx 10rpx 17rpx -7rpx #666;

	// 		.material-scroll {
	// 			display: flex;

	// 			.material-item {
	// 				height: 280rpx;
	// 				width: 25vw;
	// 				background-color: #fff;
	// 				border-radius: 17rpx;
	// 				overflow: hidden;
	// 				display: flex;
	// 				flex-direction: column;
	// 				position: relative;
	// 				margin-right: 30rpx;
	// 				text-align: center;
	// 				flex-shrink: 0;

	// 				&.active {
	// 					opacity: 0.7;

	// 					.radio {
	// 						position: absolute;
	// 						right: 17rpx;
	// 						top: 17rpx;
	// 						z-index: 1;
	// 					}
	// 				}

	// 				.image {
	// 					width: 100%;
	// 					height: 280rpx;
	// 					background: #fff;
	// 					position: relative;

	// 					image {
	// 						width: 100%;
	// 						height: 100%;
	// 						position: absolute;
	// 						top: 0;
	// 						left: 0;
	// 					}
	// 				}

	// 				.title {
	// 					font-size: 24rpx;
	// 					margin: 17rpx;
	// 					flex-shrink: 0;
	// 					flex-grow: 0;
	// 					height: 50rpx;
	// 				}

	// 				.item-btn {
	// 					height: 65.8rpx;
	// 					border-radius: 17rpx;
	// 					font-size: 30rpx;
	// 					box-sizing: border-box;
	// 					text-align: center;
	// 					line-height: 62.8rpx;
	// 					background-color: #333;
	// 					color: #fff;
	// 					margin: 17rpx;
	// 				}
	// 			}
	// 		}

	// 	}
	// }

	.list-box {
		display: grid;
		justify-content: start;
		flex-wrap: wrap;
		padding: 0 15rpx;
		grid-template-columns: repeat(2, 1fr);

		.product-item {
			width: 343rpx;
			height: 393rpx;
			flex-basis: 50%;
			text-align: center;
			/* 增加硬件加速层 */
			transform: translateZ(0);
			backface-visibility: hidden;
			perspective: 1000;
			margin-bottom: 10rpx;

			.item {
				border-radius: 20rpx;
				overflow: hidden;
				position: relative;

			}

			.picture {
				width: 343rpx;
				height: 343rpx;
			}

			.title {
				width: 100%;
				font-size: 21rpx;
				bottom: 40rpx;
				position: absolute;
				padding: 0 15rpx;
				background-color: #ffffff8c;
				height: 31rpx;
				text-align: center;
				white-space: nowrap;
				text-overflow: ellipsis;
				overflow: hidden;
			}

			.price {
				font-size: 25rpx;
				// font-weight: bold;
				text-align: center;
			}
		}
	}

	.shopping-trolley {
		position: fixed;
		background: #00000060;
		bottom: 10rpx;
		left: 17rpx;
		height: 83rpx;
		width: calc(100% - 34rpx);
		border-radius: 41rpx;
		overflow: hidden;
		box-shadow: 0px 0px 0px 1px transparent;
		transition: 0.5s;

		.badge {
			position: absolute;
			top: 3rpx;
			left: 94rpx;

			&.more10 {
				left: 82rpx;
			}

			&.more99 {
				left: 82rpx;
			}
		}

		.car {
			height: 67rpx;
			width: 67rpx;
			margin: 8rpx 34rpx;
			float: left;
		}

		.price {
			font-size: 40rpx;
			color: #fff;
			float: left;
			line-height: 83rpx;
			font-weight: 700;
		}

		.get-phone {
			position: absolute;
			width: 187rpx;
			right: 0;
			opacity: 0;
		}

		.to-order {
			background: #fff;
			color: #3D3D3D;
			float: right;
			width: 187rpx;
			height: 100%;
			font-size: 35rpx;
			font-weight: 700;
			line-height: 83rpx;
			text-align: center;
		}

		&.tShow {
			box-shadow: 0px 0px 0px 1px #33333380;
		}

		&.hide {
			bottom: -85rpx;
		}
	}
}
</style>